package com.neusoft.meal.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.meal.po.MealPlan;
import com.neusoft.meal.po.ResponseBean;
import com.neusoft.meal.service.MealPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
//@CrossOrigin("*")
@RequestMapping("/MealPlanController")
public class MealPlanController {

    @Autowired
    private MealPlanService mealPlanService;

    @GetMapping("/getAllMealPlans")
//    查询膳食日历，默认启用
    public ResponseBean<List<MealPlan>> getAllMealPlans() {
        return mealPlanService.getAllMealPlans();
    }

    @GetMapping("/{id}")
    public ResponseBean<MealPlan> getMealPlanById(@PathVariable Integer id) {
        return mealPlanService.getMealPlanById(id);
    }

    @PostMapping("/addMealPlan")
//    添加膳食计划
    public ResponseBean<Integer> addMealPlan(@RequestBody Map<String, Object> map) {
        MealPlan mealPlan = new MealPlan();
        mealPlan.setDate(LocalDate.parse((String) map.get("date")));
        mealPlan.setMealType((String) map.get("mealType"));
        mealPlan.setStatus((String) map.get("status"));
        mealPlan.setNotes((String) map.get("notes"));

        // items字段转为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        String itemsJson = null;
        try {
            itemsJson = mapper.writeValueAsString(map.get("items"));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        mealPlan.setItems(itemsJson);

        return mealPlanService.addMealPlan(mealPlan);
    }

    @PutMapping("/updateMealPlan")
//    修改膳食计划
    public ResponseBean<Integer> updateMealPlan(@RequestBody Map<String, Object> map) {
        MealPlan mealPlan = new MealPlan();
        mealPlan.setPlanId((Integer) map.get("planId"));
        mealPlan.setDate(LocalDate.parse((String) map.get("date")));
        mealPlan.setMealType((String) map.get("mealType"));
        mealPlan.setStatus((String) map.get("status"));
        mealPlan.setNotes((String) map.get("notes"));

        // items字段转为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        String itemsJson = null;
        try {
            itemsJson = mapper.writeValueAsString(map.get("items"));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        mealPlan.setItems(itemsJson);
        return mealPlanService.updateMealPlan(mealPlan);
    }

    @DeleteMapping("/{id}")
    public ResponseBean<Integer> deleteMealPlan(@PathVariable Integer id) {
        return mealPlanService.deleteMealPlan(id);
    }
}